<?php
namespace App\Common\Utill;
class Utills
{
    /**
     * 实例化redis
     * @return \Redis
     * @throws \RedisException
     */
    public static function redisObj($db=0)
    {
        $resdisHost = env('REDIS_HOST');
        $redisPort = env('REDIS_PORT');
        $redis = new \Redis();
        $redis->connect($resdisHost,$redisPort);
        $redis->select($db);
        return $redis;
    }


    /**
     * 返回结构
     * @param $data
     * @return \Illuminate\Http\JsonResponse
     */
    public static function resultData($data)
    {
        return response()->json($data)->setEncodingOptions(JSON_UNESCAPED_UNICODE);
    }

    /**
     * ai生成的唯一编码
     * @return string
     */
    public static function aiOrderSn()
    {
        $uniqueId = date('ymdHis') . str_pad(mt_rand(1, 999999),6, '0', STR_PAD_LEFT);
        return $uniqueId;
    }

    /**
     * send
     * 发起请求
     * @param $url
     * @param $data
     * @param int $second
     * @return bool|string
     */
    public static function postCurl($url, $data, $apiPassword = '', $second = 300)
    {
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        curl_setopt($ch, CURLOPT_URL, $url);
        if ($apiPassword) {
            $headers = [
                "Content-Type:application/json",
                "Authorization:Bearer {$apiPassword}"
            ];
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        } else {
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:application/json;charset=UTF-8']);
        }
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data, JSON_UNESCAPED_UNICODE));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //获取的信息以文件流的形式返回，而不是直接输出
        curl_setopt($ch, CURLOPT_HEADER, false);

        if (false !== strpos($url, "https")) {
            // 证书
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }
        $response = curl_exec($ch); // 已经获取到内容，没有输出到页面上。
        $errorno = curl_errno($ch);
        if ($errorno) {
            $errorData = curl_error($ch);
            return $errorData;
        }
        if ($response === false) {
            $error = curl_error($ch);
            return $error;
        }
        curl_close($ch);
        $response = json_decode($response, true);
        return $response;
    }
}
